<template>
  <div class="invoice-main">
    <!-- <el-card class="box-card" shadow="hover">
      <el-row>
        <el-button type="primary" class="add-invoice" @click="AddInvoive">添加</el-button>
      </el-row>
    </el-card> -->
    <el-popover placement="left" trigger="click">
			<template :loading="loading">
				<!-- 随便给个data就行，否则无法弹出 -->
				<el-checkbox v-model="checked" @change="allChange">全选</el-checkbox><br />
				<el-checkbox v-model="checked0">订单编号</el-checkbox><br />
				<el-checkbox v-model="checked1">抬头</el-checkbox><br />
				<el-checkbox v-model="checked2">税号</el-checkbox><br />
				<el-checkbox v-model="checked3">发票状态</el-checkbox><br />
				<el-checkbox v-model="checked4">发票号码</el-checkbox><br />
				<el-checkbox v-model="checked5">发票张数</el-checkbox><br />
				<el-checkbox v-model="checked12">退款凭证号</el-checkbox><br />
        <el-checkbox v-model="checked6">退款时间</el-checkbox><br />
				<el-checkbox v-model="checked7">开票金额</el-checkbox><br />
				<el-checkbox v-model="checked13">寄件日期</el-checkbox><br />
				<el-checkbox v-model="checked14">顺丰单号</el-checkbox><br />
				<el-checkbox v-model="checked8">开票时间</el-checkbox><br />
        <el-checkbox v-model="checked9">专属顾问</el-checkbox><br />
        <el-checkbox v-model="checked10">发票下载</el-checkbox><br />
			</template>
			<el-button style="float: right;margin-bottom: 5px;margin-top: 0;" slot="reference" icon='el-icon-arrow-down'>显示字段</el-button>
		</el-popover>

    <!-- 列表查找 -->
    <span class="down-execel">
      <Poptip v-model="showFilter" placement="bottom-end"  @on-popper-show ='getAllAgent'>
        <i class="el-icon-search poptip-condition-add"></i>
        <a href="javascript:;">列表查找</a>
        <div slot="content">
          <Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
            <i class="el-icon-plus poptip-condition-add"></i>
            <a href="javascript:;" class='poptip-condition-add'>添加过滤条件</a>

            <div slot="content" class="condition-list">
              <ul>
                <li v-for="(item, index) in columns" :key="index" class = 'poptip-condition-item' @click="addFilterCondition(item)">{{item.label}}</li>
              </ul>
            </div>
          </Poptip>

          <el-form :model="conditionForm" ref="conditionForm" label-min-width="120px" class="demo-dynamic" @submit.native.prevent>
            <el-form-item
                v-for="(condition, index) in conditionForm.condition"
                :label="condition.label"
                :key="condition.key"
                :prop="'condition.' + index + '.value'"
                :rules="{
                  required: true, message: condition.label +'不能为空', trigger: 'blur'
                }"
              >
                <el-date-picker
                    v-model="refund_at"
                    type="daterange"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                    @change = 'changInput'
                    :validate-event='false'
                    size="small"
                    v-if='condition.label === "退款时间"'>
                </el-date-picker>

                <el-select
                  size="small"
                  filterable
                  v-model="condition.value"
                  v-else-if='condition.label === "专属顾问"'>
                  <el-option
                    v-for="item in processOptions"
                    :key="item.id"
                    :label="item.email_work.split('@')[0].split('followup')[1]"
                    :value="item.id">
                  </el-option>
                </el-select>

              <el-date-picker
                v-model="ticket_at"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                @change = 'changInput'
                :validate-event='false'
                size="small"
                v-else-if='condition.label === "开票时间"'>
              </el-date-picker>

              <el-date-picker
                v-model="condition.value"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                @change = 'changInput'
                :validate-event='false'
                size="small"
                v-else-if='condition.label === "寄件日期"'>
              </el-date-picker>

              <el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
              <el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
            </el-form-item>
          </el-form>

          <div class= 'btns'>
            <el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
            <el-button  @click.stop="resetForm1('conditionForm')" size="mini">重置</el-button>
          </div>
        </div>
      </Poptip>
    </span>

    <el-table
      v-if="table_show"
      id="IMTable"
      ref="orderTb"
      :data="tableData"
      border
      style="width: 100%"
      height="90%"
      @sort-change='tableSortChange'
      v-loading="loading">
      <el-table-column show-overflow-tooltip prop="id" label="ID" min-width="60" align="left"  v-if="checked99">
        <template slot-scope="scope">{{(scope.$index+1)+(currentPage-1)*tableSize}}</template>
      </el-table-column>
	    <el-table-column show-overflow-tooltip  v-if="checked0" prop="order_number" label="订单编号" min-width="200" align="left" sortable='custom'>
        <template slot-scope='scope'>
          <span>
            {{ scope.row.final ? scope.row.final.order_number : scope.row.order_number }}
          </span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked3" prop="status" label="发票状态" min-width="100" align="left"></el-table-column>
	    <el-table-column show-overflow-tooltip  v-if="checked1" prop="invoice.taitou" label="抬头" min-width="180" align="left" sortable>
        <template slot-scope="scope">
          <div class="more" v-if="scope.row.invoice">{{scope.row.invoice.taitou}}</div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked2" prop="invoice.tariff_number" label="税号" min-width="180" align="left" sortable></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked4" prop="invoice_number" label="发票号码" min-width="150" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked5" prop="number" label="发票张数" min-width="110" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked12" prop="reimbursement" label="退款凭证号" min-width="130" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked7" prop="money" label="开票金额" min-width="110" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked9" prop="process_id" label="专属顾问" min-width="110" align="left" sortable='custom'>
				<template slot-scope="scope">
					<!-- <div class="more">{{scope.row.process.name}}</div> -->
					<div class="more">
						<span style="margin-right: 10px" v-if=" scope.row.final.order && scope.row.final.order.process"> {{ scope.row.final.order.process.email_work.split("@")[0].split("followup")[1] }} </span>
            <template v-if='scope.row.final'>
              <Tooltip  v-if="scope.row.final.order && scope.row.final.order.process"  content="点我留言">
                <i class="el-icon-chat-dot-round leaveWord" @click.stop="leaveWord(scope.row, 'process')"></i>
              </Tooltip>
            </template>
					</div>
				</template>
			</el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked14" prop="odd_numbers" label="顺丰单号" min-width="120" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked13" prop="mailing_data" label="寄件日期" min-width="120" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked8"  prop="ticket_at" label="开票时间" min-width="120" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip v-if="checked6" prop="refund_at" label="退款时间" min-width="120" align="left" sortable='custom'></el-table-column>
      <el-table-column v-if="checked10" prop="path" label="发票下载" min-width="120" align="left">
        <template slot-scope="scope"  v-if="scope.row.path">
          <a v-for="item in scope.row.fileArr"
            :key="item.id" :href="baseUrl + '/api/download?path='  + item.file +'/'+ item.path"
						:download="item.path" :title="item.path" class="el-icon-tickets file_sh"></a>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip fixed="right" label="操作" width="150" align="center" v-if='isSpecialCustomer && checked99'>
        <!-- v-if="(scope.row.refund === null || scope.row.refund == '' || scope.row.refund === '等待退款' )&& scope.row.status === '开票成功'" -->
        <template slot-scope="scope">
          <el-button
						size="mini"
						type="warning"
						@click.stop="isRefund(scope.row)"
						:disabled=" scope.row.refund ==='等待退款' || scope.row.refund ==='退款成功' || scope.row.status != '开票成功'" v-no-more-click:3000
            >申请退款
					</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="Number(pageSize)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 弹出框 -->
    <el-dialog :title="dialogTitle" center :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="抬头" prop="taitou" v-show="!form.id" >
          <el-autocomplete
            v-model="form.taitou"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="请输入发票抬头，必填项"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.taitou }}</div>
            </template>
          </el-autocomplete>
          <!-- <el-input v-model="form.taitou" autocomplete="off" placeholder="请输入发票抬头，必填项"></el-input> -->
        </el-form-item>

        <el-form-item label="抬头" v-show="form.id" prop="taitou" >
          <el-input v-model="form.taitou" autocomplete="off" placeholder="请输入抬头"></el-input>
        </el-form-item>
        <el-form-item label="税号" v-show="!form.id" prop="tariff_number">
          <el-autocomplete
            v-model="form.tariff_number"
            :fetch-suggestions="querySearchBytariff"
            :trigger-on-focus="false"
            placeholder="请输入税号，必填项"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <span class="addr">{{ item.tariff_number }}</span>
            </template>
          </el-autocomplete>
          <!-- <el-input v-model="form.tariff_number" autocomplete="off" placeholder="请输入18位税号，必填项"></el-input> -->
        </el-form-item>
        <el-form-item label="地址及电话">
          <el-input v-model="form.add_tel" autocomplete="off" placeholder="请输入地址及电话，非必填项"></el-input>
        </el-form-item>
        <el-form-item label="开户行及银行卡号">
          <el-input v-model="form.bank_card" autocomplete="off" placeholder="开户行及银行卡号，非必填项"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose" v-no-more-click:3000>取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" v-no-more-click:3000>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 申请退款弹出框 -->
		<el-dialog title="申请退款" center :visible.sync="showRefund" @close='closeRule2'>
			<!-- <center>
				如果您的支付方式为支付宝或微信转账，退款金额为扣除支付宝或微信平台收取0.6%手续费之后的金额。
			</center> -->
      <template >
        <el-radio style= 'margin-bottom: 10px;' v-model="radio" label="1">支付宝，微信原路退回</el-radio>
        <el-radio v-model="radio" label="2">退回至银行卡</el-radio>
      </template>
			<el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-min-width="100px" class="demo-ruleForm" >
        <el-form-item label="报销凭证号" prop="reimbursement">
          <el-input v-model.number="ruleForm2.reimbursement" placeholder="请4位数报销凭证号" ></el-input>
        </el-form-item>
        <template v-if="isShowRefund">
          <el-form-item label="银行卡号" prop="card">
            <el-input v-model.number="ruleForm2.card" placeholder="请正确填写银行卡号"></el-input>
          </el-form-item>
          <el-form-item label="持卡人姓名" prop="name">
            <el-input v-model="ruleForm2.name" placeholder="请正确填写持卡人姓名"></el-input>
          </el-form-item>
          <el-form-item label="银行卡支行" prop="bank">
            <el-input v-model="ruleForm2.bank" placeholder="银行卡支行填写格式为“XX银行XX市XX支行”，例如“中国建设银行武汉金融港支行”"></el-input>
          </el-form-item>
        </template>

			</el-form>
			<center class="submit-btn">
				<center class="submit-btn">
					<el-button v-no-more-click:3000 @click="showRefund=false">取消</el-button>
          <el-button v-no-more-click:3000 v-if="!isShowRefund" type="primary" @click="submitForm2('ruleForm2')">提交</el-button>
					<el-button v-no-more-click:3000 v-else type="primary" @click="submitForm4('ruleForm2')">下一步</el-button>
				</center>
			</center>
		</el-dialog>

		<!-- 确认退款信息弹出框 -->
		<el-dialog title="确认退款信息" center :visible.sync="showRefund2">
			<el-form  v-if="isShowRefund" :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-min-width="100px" class="demo-ruleForm">
        <el-form-item label="报销凭证号" prop="reimbursement">
          <el-input disabled type="number"  v-model.number="ruleForm2.reimbursement" placeholder="请4位数报销凭证号" oninput="if(value.length>4)value=value.slice(0,4)"></el-input>
        </el-form-item>
				<el-form-item label="银行卡号" prop="card">
					<el-input disabled v-model.number="ruleForm2.card" placeholder="请正确填写银行卡号"></el-input>
				</el-form-item>
				<el-form-item label="持卡人姓名" prop="name">
					<el-input disabled v-model="ruleForm2.name" placeholder="请正确填写持卡人姓名"></el-input>
				</el-form-item>
				<el-form-item label="银行卡支行" prop="bank">
					<el-input disabled v-model="ruleForm2.bank" placeholder="请正确填写银行卡支行"></el-input>
				</el-form-item>
			</el-form>
      <!-- <p v-else>原路退回</p> -->
			<center class="submit-btn">
				<el-button v-no-more-click:3000 @click="showRefund=true;showRefund2=false;">上一步</el-button>
				<el-button v-no-more-click:3000 type="primary" @click="submitForm2('ruleForm2')">提交</el-button>
			</center>
		</el-dialog>

    <!-- 留言输入框 -->
    <leaveWordDialog ref='leaveWordDialog' />
    <!-- 留言消息框 -->
    <promptMessage ref='promptMessage' />

  </div>
</template>
<script>
import promptMessage from '~/components/promptMessage'
import leaveWordDialog from '~/components/leaveWordDialog'
import fncSearch from '~/components/searchSrceen/fnc-search.js'
export default {
  name: "invoicesManagement",
  data() {
    return {
      table_show: true,
      checked: true,
			checked0: true,
      checked1: true,
      checked2: true,
      checked3: true,
      checked4: true,
      checked5: true,
      checked6: true,
      checked7: true,
      checked8: true,
      checked9: true,
      checked10: true,
      checked11: true,
      checked12: true,
      checked13: true,
      checked14: true,
      checked99: true,
      tableData: [],
      routeid: "alreadyInvoice",
      dialogFormVisible: false,
      changeType:'add',
      form: {},
      dialogTitle: "添加发票信息",
      rules: {
        taitou: [
          { required: true, message: "请输入发票抬头", trigger: "blur" }
        ],
        tariff_number: [
          { required: true, message: "请输入税号", trigger: "blur" },
          { min: 18, max: 18, message: "18位税号", trigger: "blur" }
        ]
      },
      restaurants: [], //发票抬头匹配

      restaurantsBytariff: [], // 税号匹配
      tableSize: 10, //一页几条
      tableStart: 0, //table数组过滤的第一条索引
      tableEnd: 10, //table数组过滤的最后一条索引
      currentPage: 1, //目前在第几页
      loading: true,
      pageSizes: [25,50], //一页可以几条
      pageSize: 25, //一页可以几条
      total:0,
      baseUrl: global.baseurl,
      showFilter: false, // 控制显示筛选条件
      showFilterCondition: false,
      conditionForm: {
        condition: []
      }, //筛选条件
      columns: [

        {
          label: '订单编号',
          id: 1,
          parameter: 'order_number',
        },
        {
          label: '抬头',
          id: 2,
          parameter: 'taitou',
        },
        {
          label: '税号',
          id: 3,
          parameter: 'tariff_number',
        },
        {
          label: '发票号码',
          id: 5,
          parameter: 'invoice_number',
        },
        {
          label: '退款凭证号',
          id: 13,
          parameter: 'reimbursement',
        },
        {
          label: '发票张数',
          id: 6,
          parameter: 'number',
        },
        {
          label: '开票金额',
          id: 7,
          parameter: 'money',
        },
        {
          label: '专属顾问',
          id: 7,
          parameter: 'process_id',
        },
        {
          label: '顺丰单号',
          id: 14,
          parameter: 'odd_numbers',
        },
        {
          label: '寄件日期',
          id: 13,
          parameter: 'mailing_data'
        },
        {
          label: '退款时间',
          id: 11,
          parameter: 'refund_at'
        },
        {
          label: '开票时间',
          id: 12,
          parameter: 'ticket_at'
        },
      ],
      lastTime: 0,
      searchValue: '',
      refund_at: [],
      ticket_at: [],
      fileArr: [],
      paramsByInv: {
        status: "开票成功",
      },
      showRefund: false,
      showRefund2: false,
      ruleForm2: {
        reimbursement: '',
        card: '',
        name: '',
        bank: ''
      },
      rules2: {
        reimbursement: [{required: true,message: '请填写报销凭证号',trigger: 'blur'}],
        card: [{
          required: true,
          message: '请填写银行卡号',
          trigger: 'blur'
        },
        {
          type: 'number', message: '银行卡号必须为数字值', trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请填写持卡人姓名',
          trigger: 'blur'
        }],
        bank: [{
          required: true,
          message: '请填写银行支行地址',
          trigger: 'blur'
        }]
      },
      refundID: '',
      radio: '1',
      formProcess: {},
      patentee: null
    };
  },
  watch: {
    selectArr(val) {
        this.table_show = false
        this.$nextTick(() => {
          this.table_show = true
        })
        setTimeout(() => {
          this.$nextTick(() => {
            this.gwm()
          })
        }, 300)
				if (val.some(v => v == false)) {
					this.checked = false
				} else {
					this.checked = true
        }
        if (val.every(v => v == false)) {
          this.checked99 = false
        } else {
          this.checked99 = true
        }
			},
  },
  components: {
    promptMessage,
    leaveWordDialog,
    fncSearch
  },
  computed: {
    isShowRefund () {
      if(this.radio == '1') {
        return false
      } else {
        return true
      }
    },
    selectArr() {
      let arr = [this.checked0, this.checked1, this.checked2, this.checked3, this.checked4, this.checked5, this.checked6, this.checked7, this.checked8, this.checked9, this.checked10, this.checked11, this.checked12, this.checked13, this.checked14]
      return arr
    },
    isSpecialCustomer () {
      // let patentNameArr = []
      // for(let i = 0; i < this.tableData.length; i++) {
      //   if (this.tableData[i].final.order) {
      //     patentNameArr.push(this.tableData[i].final.order.patent_user)
      //   }
      // }

      // if(patentNameArr.join(',').search('协和') == -1) {
      //   return false
      // } else {
      //   return true
      // }
      if (this.patentee) {
        if (this.patentee.search('协和') == -1 ) {
          return false
        } else {
          return true
        }
      } else {
        return false
      }

    }
  },
  created() {
    this.patentee = this.$store.state.user.liaison.organization
    this.getInvoiceList('created');
    this.getAllInv();
  },
  methods: {
    gwm() {
				//水印,非管理员要设置
				if (this.$store.state.user.role_id != 1
					&& this.$route.path != '/admin/register'
					&& this.$route.path != '/admin/personalCenter/dstribution'
					&& this.$route.path != '/admin/personalCenter/myPurse'
					&& this.$route.path != '/admin/activityList/activityConfig'
					&& this.$route.path != '/admin/activityList/sysConfig'
					&& this.$route.path !='/admin/login'
					&& this.$route.path != '/admin/agentImprove'
					&& this.$route.path != '/order/login') {
					let that = this;
					let gwm = require('gwm');
					gwm.creation({
						'txt': that.$store.state.user.name,
						'container': '.el-table', //#gwm
						'fontSize': 40
					})
				}
			},
    allChange(val) {
      if(val) {
          this.checked0 = true;
					this.checked1 = true;
					this.checked2 = true;
					this.checked3 = true;
					this.checked4 = true;
					this.checked5 = true;
					this.checked6 = true;
					this.checked7 = true;
					this.checked8 = true;
					this.checked9 = true;
					this.checked10 = true;
					this.checked11 = true;
					this.checked12 = true;
					this.checked13 = true;
					this.checked14 = true;
        } else {
          this.checked0 = false;
					this.checked1 = false;
					this.checked2 = false;
					this.checked3 = false;
					this.checked4 = false;
					this.checked5 = false;
					this.checked6 = false;
					this.checked7 = false;
					this.checked8 = false;
					this.checked9 = false;
					this.checked10 = false;
					this.checked11 = false;
					this.checked12 = false;
					this.checked13 = false;
					this.checked14 = false;
        }
    },
    leaveWord (row, role) {
      if (row.final) {
        this.$refs.leaveWordDialog.showLeaveWord(row.final, role)

      }
    },
    getInvoiceList(type) {
      let that = this;
      that.$axios
        .get("api/consumer/invoice", {
          params: {
            status: '开票成功',
            sort_str: 'created_at',
            sort_order: 'desc'
          }
        })
        .then(res => {
          that.loading = false;
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.tableSize = res.data.page.per_page;
            this.tableEnd = res.data.page.per_page;
            this.total = res.data.page.total;

            for (let i = 0; i < this.tableData.length; i++) {
              this.imgs(this.tableData[i])
            }
            if (type) {
              this.table_show = false
              this.$nextTick(() => {
                this.table_show = true
              })
            }

          } else {
            this.$message.error("错误，请重试");
          }
        })

        .catch(err => {
          this.$message.error(err);
        });
    },
    //添加
    AddInvoive() {
      this.changeType = 'add'
      this.dialogTitle = "添加发票信息";
      this.dialogFormVisible = true;
    },
    //修改
    editInvoice(val) {
      this.form = val;
      this.dialogTitle = "修改发票信息";
      this.dialogFormVisible = true;
      this.changeType = 'edit'
    },
    //将数据提交给后台(添加/修改)
    submitForm(formName) {
      //验证通过
      let that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.changeType == 'edit') {
            //修改
            that.$axios
              .put(
                "api/consumer/" + that.form.id + "/updateInvoice",
                {
                  invoice: that.form.id,
                  taitou: that.form.taitou,
                  add_tel: that.form.add_tel,
                  bank_card: that.form.bank_card
                }
              )
              .then(res => {
                if (res.data.code == 200) {
                  this.$message.success("修改成功");
                  this.resetForm("ruleForm");
                  this.getInvoiceList();
                  this.getAllInv();
                }
              })
              .catch(err => {
                this.$message.error(err);
              });


          } else  {
            //添加
            var user = that.$store.state.user;
            that.form.consumer_id = user.id;
            that.$axios
              .post("/api/consumer/addInvoice", that.form)
              .then(res => {
                if (res.data.code == 200) {
                  that.$message.success("添加成功");
                  that.getInvoiceList();
                  this.resetForm("ruleForm");
                } else {
                  that.$message.error(res.data.message);
                  this.resetForm("ruleForm");
                }
              })
              .catch(err => {
                that.$message.error("添加失败");
                that.dialogFormVisible = false;
              });
          }
        } else {
          this.$message.error("信息填写错误，请重新输入");
        }
      });
    },

    //删除发票
    delInvoices(val) {
      this.$confirm("是否删除该发票?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning"
      })
        .then(() => {
          this.$axios
            .delete(
              "api/consumer/" + val.id + "/deleteInvoice",
              {
                invoice: val.id
              }
            )
            .then(res => {
              if (res.data.code == 200) {
                this.$message.success("删除成功");
                this.resetForm("ruleForm");
                this.getAllInv();
              } else {
                this.$message.error("删除失败，请重试");
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //关闭弹出层
    handleClose() {
      this.resetForm("ruleForm");
    },
    //重置数据
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.form = {};
      this.$refs[formName].resetFields();
      this.getInvoiceList();
    },
    //获取所有发票信息
    getAllInv() {
      this.$axios
        .get("api/inv")
        .then(({ data }) => {
          let obj = data.data;
          for (const i in obj) {
            obj[i].value = obj[i].taitou;
          }
          this.restaurants = obj;
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //输入抬头模糊匹配
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = [];
      if (restaurants.length > 0) {
        for (const i in restaurants) {
          restaurants[i].value = restaurants[i].taitou
        }
        results = results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
      }
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //税号模糊匹配
    querySearchBytariff(queryString, cb) {
      var restaurants = this.restaurants;
      var results = [];
      if (restaurants.length > 0) {
        //value改为税号
        for (const i in restaurants) {
          restaurants[i].value = restaurants[i].tariff_number
        }
        results = results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
      }
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //匹配
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
        );
      };
    },

    //模糊匹配赋值
    handleSelect(item) {
      var obj = {
        taitou: item.taitou,
        tariff_number: item.tariff_number,
        bank_card: item.bank_card,
        add_tel: item.add_tel
      };
      this.form = obj;
      this.$refs["ruleForm"].clearValidate();
    },
    //选择一页几条
    handleSizeChange(size) {
      this.paramsByInv.perPage = size
      this.paramsByInv.page = 1
      this.$axios.get('/api/consumer/invoice',{
        params: this.paramsByInv
        }
      )
      .then(res => {
        this.tableData = res.data.data;
        this.pageSize = res.data.page.per_page;
        this.tableSize = res.data.page.per_page;
        this.tableEnd = res.data.page.per_page;
        this.total = res.data.page.total;
      })
    },
    //选择第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      let params =  this.paramsByInv
      let page = val;
      let that = this;
      that.$axios.get('api/consumer/invoice?page='+page, {
        params
      })
      .then(res => {
        that.loading = false;
        that.tableData = res.data.data;
        this.pageSize = res.data.page.per_page;
        this.tableSize = res.data.page.per_page;
        this.tableEnd = res.data.page.per_page;
        this.total = res.data.page.total;
        for (let i = 0; i < this.tableData.length; i++) {
          this.imgs(this.tableData[i])
        }
      })
    },

    submitsearch(formName) {
				let that = this
				this.$refs[formName].validate((valid, prop) => {
				// this.$refs[formName].clearValidate();
					let props = []
					for (let k in prop) {
						props.push(prop[k][0].field)

						if (prop[k][0].message = '提交时间不能为空') {
							if (that.submitTime) {
								if (that.submitTime.length > 0) {
									that.$refs[formName].clearValidate([prop[k][0].field])
									// that.search()
									let timeIndex = props.indexOf('提交时间不能为空')
									props.splice(timeIndex, 1)
								}
							} else {
								return false
							}
						}

					}
					if (props.length) {
						that.$refs[formName].validateField(props, (valid2) => {
							if(valid2) {
								return false;
							} else {
								that.search()
                this.showFilter = false
							}

						})
					} else {
						that.search()
            this.showFilter = false
					}
        })
			},
    search() {
      this.currentPage = 1
      for (var i = 0; i < this.conditionForm.condition.length; i++) {
        let a = this.conditionForm.condition[i].parameter
        if (this.conditionForm.condition[i].parameter === 'refund_at') {
          this.paramsByInv.refund_start_time = this.refund_at[0]
          this.paramsByInv.refund_end_time = this.refund_at[1]
        }
        if (this.conditionForm.condition[i].parameter === 'ticket_at') {
          this.paramsByInv.ticket_start_time = this.ticket_at[0]
          this.paramsByInv.ticket_end_time = this.ticket_at[1]
        }
        this.paramsByInv[a] = this.conditionForm.condition[i].value
      }

      delete this.paramsByInv.sort_str
      delete this.paramsByInv.sort_order
      this.$refs['orderTb'].clearSort()

      let that = this;
      that.loading = true;
      that.$axios
        .get("api/consumer/invoice", {
          params: this.paramsByInv
        })
        .then(res => {
            console.log(res, 'res.data')
          that.loading = false;
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.tableSize = res.data.page.per_page;
            this.tableEnd = res.data.page.per_page;
            this.total = res.data.page.total;
            for (let i = 0; i < this.tableData.length; i++) {
              this.imgs(this.tableData[i])
            }
          } else {
            this.$message.error("错误，请重试");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });

    },

    // 添加条件筛选
    addFilterCondition(item) {
      let filterItem = {
        value: '',
        label: item.label,
        parameter: item.parameter,
        key: Date.now()
      }
      if (this.conditionForm.condition.length > 0) {
      let conditionlabels = []
      for(let i = 0; i < this.conditionForm.condition.length; i++) {
        conditionlabels.push(this.conditionForm.condition[i].label)
      }
        let Check = conditionlabels.indexOf(item.label)
        Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
      } else {
        this.conditionForm.condition.push(filterItem)
      }

      this.showFilterCondition = false;

    },

    resetForm1(formName) {
      this.showFilter = true
      this.$refs['orderTb'].clearSort()
      this.conditionForm.condition.forEach(v => {
        if (v.value) {
          v.value = null
        }
      });
      this.refund_at = []
      this.ticket_at = []
      this.formProcess = {}
      this.paramsByInv = {
        status: "开票成功",
      }
      this.$nextTick(() => {
        this.$refs[formName].clearValidate()
      })
      // this.getInvoiceList()
      // this.showFilter = false
      // this.showFilterCondition = false
    },
    removeDomain(item) {
      this.showFilter = true
      delete this.paramsByInv[item.parameter]
      let index = this.conditionForm.condition.indexOf(item)
      if (index !== -1) {
        this.conditionForm.condition.splice(index, 1)
      }
      if (item.label === '退款时间') {
          this.refund_at = []
          delete this.paramsByInv.refund_start_time
					delete this.paramsByInv.refund_end_time
      }
      if (item.label === '开票时间') {
          this.ticket_at = []
          delete this.paramsByInv.ticket_start_time
					delete this.paramsByInv.ticket_end_time
      }
      if (item.label === '专属顾问') {
        this.formProcess = {}
      }
      this.search()
    },
    changInput () {
      this.$refs['conditionForm'].clearValidate();
    },
    imgs (data) {
      //文件 切分组件
      if (data.path == null || data.path == "") {} else {
        let file_Arr = data.path.split("&");
        data.fileArr = [];
        for (const i in file_Arr) {
          let itemobj = {
            id: i + 1,
            path: file_Arr[i],
            file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data.fileArr.push(itemobj);
        }
      }
      if (data.review_file == null || data.review_file == "") {} else {
        let file_Arr = data.path.split("&");
        data.reviewFile = [];
        for (const i in file_Arr) {
          let itemobj = {
            id: i + 1,
            path: file_Arr[i],
            file: ''
          };
          let itemArr = itemobj.path.split("/")
          itemobj.path = itemArr[itemArr.length - 1]
          itemobj.file = itemArr.slice(0, 2).join("/");
          data.reviewFile.push(itemobj);
        }
      }
    },
    isRefund(row) {
      let that = this;
      this.$confirm('<div id="myOrder"><div class="tableTitle"><span class="midText">' +
        '<h3 class="center-title">退费须知</h3>' +
        '</span></div>' +
        // '<center >' +
        // '<b class="center-title">（仅限已缴费用户使用，<b class="center-title2">未缴费用户请勿申请</b>）</b>' +
        // '</center>' +
        '<br />' +
        '<p style="text-align: left;">' +
        '<b class="center-title3">&emsp;&emsp;退费方式为原路返回，即退回到缴费渠道，例如用微信缴费，则退回到微信缴费账户；退费截图发送至联络人邮箱</b><br />' +
        '#有疑问请联系：严经理，13164620214</p></div>', '', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '申请退款',
          cancelButtonText: '取消',
          center: true,
        })
      .then(() => {
        that.refund(row.id);
      })
      .catch(action => {})
    },
    refund(id) {
      this.showRefund = true;
      this.refundID = id;
      // this.refundIndex = index;
      //this.tableData[index].invoice_record.refund = '等待退款';
    },
    submitForm2(formName) {
      let that = this;
      if (this.isShowRefund) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            that.$axios.put('/api/consumer/refund/' + that.refundID, {
              invoiceRecord: that.refundID,
              card: that.ruleForm2.card,
              name: that.ruleForm2.name,
              bank: that.ruleForm2.bank,
              reimbursement: `${that.ruleForm2.reimbursement}`
            })
            .then(res => {
              if (res.data.code == 200) {
                that.$message({
                  message: '申请退款成功，请等待处理结果！',
                  type: 'success',
                  duration: 3000
                });
                // that.getInvoiceList()
                this.search()
                // that.verify = false
                //不再显示对应列的“退款申请”按钮
                // this.tableData[this.refundIndex].invoice_record.invoice_number = null
                that.showRefund = false;
                that.showRefund2 = false;
              } else {
                that.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            })
          } else {
            return false;
          }
        });
      } else {
        that.$refs[formName].validateField('reimbursement', err => {
          if (!err) {
            that.$axios.put('/api/consumer/refund/' + that.refundID, {
              invoiceRecord: that.refundID,
              reimbursement: `${that.ruleForm2.reimbursement}`
            })
          .then(res => {
            if (res.data.code == 200) {
              that.$message({
                message: '申请退款成功，请等待处理结果！',
                type: 'success',
                duration: 3000
              });
              // that.getInvoiceList()
              this.search()
              // that.verify = false
              //不再显示对应列的“退款申请”按钮
              // this.tableData[this.refundIndex].invoice_record.invoice_number = null
              that.showRefund = false;
              that.showRefund2 = false;
            } else {
              that.$message({
                message: res.data.message,
                type: 'error'
              });
            }
          })
          }
        })
      }

    },
    closeRule2 () {
      this.ruleForm2.card = ''
      this.ruleForm2.name = ''
      this.ruleForm2.bank = ''
    },
    submitForm4(formName) {
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.showRefund2 = true;
        } else {
          return false;
        }
      });
    },
    tableSortChange(column) {
      if (column.order === 'descending') {
        this.paramsByInv.sort_str = column.prop
        this.paramsByInv.sort_order = 'desc'
      } else if (column.order === 'ascending'){
        this.paramsByInv.sort_str = column.prop
        this.paramsByInv.sort_order = 'asc'
      } else {
        delete this.paramsByInv.sort_str
        delete this.paramsByInv.sort_order
      }
      if (column.prop == 'invoice.taitou' || column.prop == 'invoice.tariff_number') {
        this.loading = false;
        return
      }
      this.loading = true;
      this.$axios
        .get("api/consumer/invoice", {
          params: this.paramsByInv
        })
        .then(res => {
          this.loading = false;
          if (res.data.code == 200) {
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.tableSize = res.data.page.per_page;
            this.tableEnd = res.data.page.per_page;
            this.total = res.data.page.total;
            for (let i = 0; i < this.tableData.length; i++) {
              this.imgs(this.tableData[i])
            }
          } else {
            this.$message.error("错误，请重试");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //获取所有专属顾问
    getAllAgent() {
      this.$axios.get('api/user/process')
        .then(res => {
          if (res.data.code == 200) {
            this.processOptions = res.data.data
          }
        })
        .catch(err => {
          this.$message({
            type: "err",
            message: err
          })
        })
    },
  }
};
</script>

<style lang="less">
.invoice-main {
  height: 100%; //撑满表格
  // #IMTable {
  //   height: 70%; //撑满表格
  // }
  .box-card {
    margin-bottom: 20px;
    .add-invoice {
      float: left;
    }
  }
  // .el-autocomplete {
  //   display: block;
  // }
  .pagination {
    margin-top: 30px; /*no*/
  }
}
  .el-main .ivu-poptip .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner{
		min-width: 480px ;
		// height: 300px;
		overflow-y:scroll;

	}

	.poptip-condition {
		display: block;
		margin-top: 10px;
		.poptip-condition-item {
			line-height: 25px;
			cursor:pointer;
		}
		.poptip-condition-add {
			font-size: 14px;
		}
	}
	.demo-dynamic {
		padding-left: 10px;
		.el-form-item {
			margin-bottom: 12px;
		}
		.el-input {
			width: 240px;
		}
		.el-date-editor {
			width: 240px;
		}
		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}
		.el-form-item__error {
			padding-top: 0 ;
		}
  }

  .down-execel {
    display: block;
    height: 40px;
    line-height: 40px;
    color: #333333;
    font-size: 14px;
    float: right;
    margin-right: 20px;
  }

	.el-main .poptip-condition .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 180px;
  }

  .btns {
		margin-top: 10px;
  }
  .file_sh {
    font-size: 26px;
    margin-right: 10px;
  }
  .processInput {
    display: inline-block !important;
  }
</style>>
